<?php

namespace module\manage\controller;

use app\Controller;
use app\model\auth\Admin as Model;
use Firebase\JWT\JWT;
use app\model\auth\Menu;

class Me extends Controller
{
    /**
     * 详情.
     * 
     */
    public function index()
    {
        $model = Model::scope('user')->field(['name', 'mobile', 'status', 'avatar', 'role_id'])->findOrEmpty();
        if($model->isEmpty()){
            return json(['code' => 401, 'msg' => '当前账号不存在']);
        }
        if($model->status !== 2){
            return json(['code' => 401, 'msg' => '当前账号异常']);
        }
        $role = $model->role;
        // 获取token
        $data = [
            'role' => $role->name,
            'roles' => $role->perms,
            'menus' => Menu::tree(['value' => 'id', 'label' => 'name', 'pid' => 'pid'])
        ]; //参数为用户认证的信息，请自行添加
        // redis()->hset('ManageAccessTokenList', $data['token'], $data + ['login_at' => time()]);
        return json($data + $model->toArray());
    }
    /**
     * 更新.
     */
    public function update()
    {
        $model = Model::scope('user')->findOrFail();
        $model->save($this->request->put());
        return json($model->tpoArray());
    }
    /**
     * 删除.
     * 
     */
    public function del()
    {
        $model = Model::scope('user')->findOrFail();
        $model->delete();
        return json($model->toArray());
    }
    /**
     * 修改密码.
     * 
     */
    public function reset()
    {
        $post = $this->request->post();
        $model = Model::scope('user')->field(['id', 'status', 'password'])->findOrEmpty();
        if($model->isEmpty()){
            return json(['code' => 0, 'msg' => '当前账号不存在']);
        }
        if($model->status !== 2){
            return json(['code' => 0, 'msg' => '党章账号异常']);
        }
        if(!password_verify($post['origin'], $model->password)){
            return json(['code' => 0, 'msg' => '密码错误']);
        }
        $model->save(['password' => password_hash($post['password'], PASSWORD_BCRYPT)]);
        return json($model->toArray());
    }
    /**
     * 退出.
     * 
     */
    public function logout()
    {
        // $model = Model::scope('user')->findOrFail();
        // $model->delete();
        return json([]);
    }
}
